package com.lanwf.admin.sys.menu;

import com.jfinal.aop.Inject;
import com.jfinal.core.Path;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.lanwf.admin.BaseController;
import com.lanwf.IAdminIndexController;
import com.lanwf.admin.sys.PermissionService;
import com.lanwf.common.model.SysMenu;
import com.lanwf.common.model.SysOperate;
import com.lanwf.common.model.SysPermission;
import com.lanwf.admin.utils.CommonUtil;
import com.lanwf.admin.vo.Ztree;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @Auther: lanWf
 * @Date: 2021/12/24 10:55
 * @Description:
 */
@Path(value = "/admin/menu", viewPath = "/admin/sys/menu")
public class MenuAdminController extends BaseController implements IAdminIndexController {


    @Inject
    PermissionService permissionService;

    @Override
    public void index() {
        set("permission",permissionService.getPermission(getAccountId(),getInt(0)));
        render("index.html");
    }

    @Override
    public void paginate() {
        Integer p = getInt("pageNum", 1);
        Integer s = getInt("pageSize", 1000);

        String orderByColumn = get("orderByColumn", "");

        String name = get("name", "");

        List<Object> param = new ArrayList<>();
        String sql = " from sys_menu where 1=1 ";

        if (StrKit.notBlank(name)) {
            sql += " and name like ? or code like ? ";
            param.add("%" + name + "%");
            param.add("%" + name + "%");
        }

        if (StrKit.notBlank(orderByColumn)) {
            sql += " order by sort asc,create asc";
        }
        Page<SysMenu> paginate = SysMenu.dao.paginate(p, s, "select *", sql, param.toArray());

        List<SysOperate> operates = SysOperate.dao.findAll();

        if(paginate.getList() != null && paginate.getList().size() > 0){
            paginate.getList().forEach(a->{

                String strId = "";
                if(StringUtils.isNotBlank(a.getOperateIds())){
                    String[] split = a.getOperateIds().split(",");
                    for (String id : split) {
                        for (SysOperate operate : operates) {
                            if(Integer.valueOf(id).equals(operate.getId())){
                                strId += operate.getName() +" ";
                            }
                        }
                    }
                }
                a.setOperateIds(strId);
            });
        }


        renderJson( paginate.getList());
    }

    @Override
    public void add() {
        set("operates",SysOperate.dao.find("select * from sys_operate order by sort desc,create_time desc"));
        set("menus",SysMenu.dao.find("select * from sys_menu where pid = 0 order by sort desc,create_time desc"));
        render("add_edit.html");
    }

    @Override
    public void save() {
        getFile();
        SysMenu model = getModel(SysMenu.class, "menu");
        model.set("create_time", new Date()).save();

        //编辑 路径+id
        if(model.getPid() != null && model.getPid() > 0) {
            model.setLink(model.getLink() + "/" + model.getId());
            model.update();
        }

        CommonUtil.setCache("listMenus",null);
        renderJson(Ret.ok().set("msg", "添加成功"));
    }

    @Override
    public void edit() {
        Integer id = getInt(0);
        SysMenu sysMenu = SysMenu.dao.findById(id);
        set("menu", sysMenu);

        List<SysOperate> operates = SysOperate.dao.find("select * from sys_operate order by sort desc,create_time desc");

        for (SysOperate o : operates) {
            o.put("active",0);
            if(StringUtils.isNotBlank(sysMenu.getOperateIds())){
                String[] split = sysMenu.getOperateIds().split(",");
                for (String s : split) {
                    if(Integer.valueOf(s).equals(o.getId())){
                        o.put("active",1);
                    }
                }
            }
        }

        set("operates",operates);
        set("menus",SysMenu.dao.find("select * from sys_menu where pid = 0 order by sort desc,create_time desc"));

        render("add_edit.html");
    }

    @Override
    public void update() {
        getFile();
        SysMenu model = getModel(SysMenu.class, "menu");
        model.update();

        Db.update("update sys_permission set pid = ? where menu_id = ? ",model.getPid(),model.getId());
        CommonUtil.setCache("listMenus",null);
        renderJson(Ret.ok().set("msg", "修改成功"));
    }

    @Override
    public void delete() {
        Integer id = getInt(0);
        SysMenu.dao.deleteById(id);
        renderJson(Ret.ok().set("msg", "删除成功"));
    }

    /**
     * 名字去重判断
     */
    public void nameUnique() {
        Integer id = getInt("id");
        String name = get("name");

        SysMenu first = null;
        if (id != null) {
            first = SysMenu.dao.findFirst("select * from sys_menu where id != ? and name = ? ", id, name);
        } else {
            first = SysMenu.dao.findFirst("select * from sys_menu where name = ? ",name);
        }

        if (first != null) {
            renderJson(Ret.fail("msg", "名称重复"));
            return;
        }
        renderJson(Ret.ok("msg", "名称可用"));
    }

    /**
     * 权限树状结构 显示
     */
    public void roleMenuTreeData(){
        String addEdit = get(0, "add");
        Integer id = getInt(1);
        renderJson("add".equals(addEdit) ? addZtree() : editZtree(id));
    }

    private List<Ztree> addZtree(){
        List<SysMenu> sysMenus = SysMenu.dao.find("select * from sys_menu order by sort asc,create_time asc");
        List<Ztree> ztrees= new ArrayList<>();

        //查询除了目录的菜单的操作权限
        List<SysMenu> menus = SysMenu.dao.find("select * from sys_menu where pid > 0 order by sort desc");

        for (SysMenu p : sysMenus) {
            Ztree z = new Ztree();

            String header = (p.getPid() == 0) ? "a" : "b";

            z.setId(header+p.getId().toString());
            z.setName(p.getName());

            if("a".equals(header)){
                z.setpId(p.getPid().toString());
            }else {
                z.setpId("a"+p.getPid());
            }

            z.setTitle(p.getName());
            ztrees.add(z);

        }

        for (SysMenu menu : menus) {
            if(StringUtils.isNotBlank(menu.getOperateIds())){
                List<SysOperate> ps = SysOperate.dao.find("select * from sys_operate where id in ( " + menu.getOperateIds() + ")");
                for (SysOperate p : ps) {
                    Ztree z = new Ztree();
                    z.setId(menu.getId()+"_"+p.getId().toString());//带有a证明是操作表的id
                    z.setName(p.getName());
                    z.setpId("b"+menu.getId());
                    z.setTitle(p.getName());
                    ztrees.add(z);
                }
            }
        }
        return ztrees;
    }


    private List<Ztree> editZtree(Integer id){
        List<Ztree> ztrees= new ArrayList<>();

        List<SysMenu> sysMenus = SysMenu.dao.find("select * from sys_menu order by sort asc,create_time asc");
        //查询除了目录的菜单的操作权限
        List<SysMenu> menus = SysMenu.dao.find("select * from sys_menu where pid > 0 order by sort desc");


        HashMap<String, SysPermission> setData = new HashMap<>();
        List<SysPermission> sysPermissions = SysPermission.dao.find("select * from sys_permission where account_id = ? ", id);
        for (SysPermission ps : sysPermissions) {
            setData.put(ps.getMenuId().toString(),ps);
        }
        for (SysPermission ps : sysPermissions) {
            setData.put(ps.getPid().toString(),ps);
        }

        for (SysMenu p : sysMenus) {
            Ztree z = new Ztree();

            String header = (p.getPid() == 0) ? "a" : "b";

            z.setId(header+p.getId().toString());
            z.setName(p.getName());

            if(setData.get(p.getId().toString()) != null){
                z.setChecked(true);
            }

            if("a".equals(header)){
                z.setpId(p.getPid().toString());
            }else {
                z.setpId("a"+p.getPid());
            }

            z.setTitle(p.getName());
            ztrees.add(z);
        }

        for (SysMenu menu : menus) {

            SysPermission permission = setData.get(menu.getId().toString());

            if(StringUtils.isNotBlank(menu.getOperateIds())){
                List<SysOperate> ps = SysOperate.dao.find("select * from sys_operate where id in ( " + menu.getOperateIds() + ")");

                for (SysOperate p : ps) {
                    Ztree z = new Ztree();
                    z.setId(menu.getId()+"_"+p.getId().toString());//带有a证明是操作表的id
                    z.setName(p.getName());
                    z.setpId("b"+menu.getId());
                    z.setTitle(p.getName());

                    if(permission != null && StringUtils.isNotBlank(permission.getOperates())){
                        String operates = permission.getOperates();
                        String[] split = operates.split(",");
                        for (String s : split) {
                            if(p.getId().toString().equals(s)){
                                z.setChecked(true);
                            }
                        }
                    }
                    ztrees.add(z);
                }
            }
        }
        return ztrees;
    }

}